<?php
	require '../Class/autoload.php';
	date_default_timezone_set("Asia/Chongqing");


	//sleep(5);
	//验证远程token
	//$token = I('remote_token','post');
	$token = $_REQUEST['remote_token'];
	if(!$token || !CheckRemoteToken($token)){
		//exit('10001');
	}


	$db_name = I('db_name','post');
	$db_host = I('db_host','post');
	if(!$db_name || !$db_host){
		exit('100004');   //缺少库信息
	}
	$config['db_name'] = $db_name;
	$config['db_host'] = $db_host;




	switch (@$_REQUEST['type']) {


		default :
			echo 'default';

			break;


		//获取帮砍用户列表
		case 'GetFreeUserList':
			$order_numb = @$_POST['order_numb'];
			$uri = @$_POST['uri'];
			if(!$order_numb || !$uri){
				exit;
			}
			$pdo = MyPdoIndex::init($config);
			$sql = 'select openid,name,header,price from shop_free_order_user where order_numb = ?';
			//$sql = 'select openid,name,header,price from shop_free_order_user';
			$res = $pdo->dql($sql,array($order_numb));
			if($res){
				//echo json_encode($res);
				$data = array();
				foreach($res as $v){
					$tmp = array();
					$tmp[] = $v['openid'];
					$tmp[] = $v['name'];
					$tmp[] = $v['header'];
					$tmp[] = $v['price'];
					array_push($data,$tmp);
				}
				SaveUpyunAndtag1AndViewData($config,$data,$uri,'',1);
			}
			//注：帮砍列表，必须有数据，因为在订单生成时至少会有自己的砍价，如果无数据说明异常，则无需缓存到upyun
			break;




		//获取或创建砍价订单
		case 'GetOrCreateFreeOrder':
			$free_id = intval(@$_POST['free_id']);
			$order_uri = @$_POST['order_uri'];
			$order_numb = @$_POST['order_number'];
			$openid = @$_POST['openid'];
			$nickName = @$_POST['nickName'];
			$headerImg = @$_POST['headerImg'];
			if(!$free_id || !$order_numb ||!$openid || !$nickName || !$headerImg){
				exit;
			}


			$pdo = MyPdoIndex::init($config);
			$sql1 = "select * from shop_free_order where order_numb = ?";
			$res1 = $pdo->dql($sql1,array($order_numb),1);
			if($res1){		//订单存在
				$arr3 = array(
					$res1['id'],
					$res1['order_numb'],
					$res1['openid'],
					intval($res1['free_id']),
					$res1['store_id'],
					$res1['title'],
					$res1['banner'],
					$res1['price'],
					$res1['price_free'],
					$res1['ctime'],
					$res1['stat'],
					$res1['tag1']
				);
				//缓存数据及tag1到upyun,并显示
				SaveUpyunAndtag1AndViewData($config,$arr3,$order_uri,'11');
			}else{ 	//订单不存在，则创建
				$sql2 = "select store_id,title,price,banner from shop_free where id = ?";	//获取砍价商品信息
				$res2 = $pdo->dql($sql2,array($free_id),1);
				if($res2){
					$price_free = round($res2['price']/2+rand(1,99)/rand(100,199),2); //砍去的价格
//					echo $price_free;exit;
					$sql3 = "insert into shop_free_order values(null,?,?,?,?,?,?,?,?,?,?,?)";	//创建砍价订单
					$arr3 = array(
						$order_numb,
						$openid,
						$free_id,
							$res2['store_id'],
							$res2['title'],
							$res2['banner'],
							''.$res2['price'],
							''.$price_free,
						''.time(),
						'1',
						1
					);
					$new_order_id = $pdo->dml($sql3,$arr3);
					if($new_order_id){
						array_unshift($arr3,$new_order_id);
						SaveUpyunAndtag1AndViewData($config,$arr3,$order_uri,'11',0,0);
						$arr3[11] = '0';
						echo json_encode($arr3);
						/*
							逻辑说明：新订单将数据缓存到upyun,然后将版本标识置为0表示首砍。
							当小程序中再次访问时，由于版本标识不一致，会更新数据，当标识不为0时则不再弹出首砍提示。
						*/
						//记录帮砍记录
						RecordFreeUser($pdo,$order_numb,$openid,$nickName,$headerImg,$price_free);
					}
				}else{
					exit;
				}

			}
			break;



		//获取用户openid
		case 'GetOpenid':
			$code = $_POST['code'];
			if(!$code){
				exit;
			}
			$appid = 'wx59b656c24cc6c189';
			$secret = '36351f86780dc2d8555bed73b5173646';
			$url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";

			echo  CurlForGet($url);
			break;


		//获取砍价商品列表
		case 'GetFreeGoodsList':
			$pnow = intval(@$_POST['pnow'])?intval($_POST['pnow']):1;
			$cache_uri = $_POST['cache_uri'];
			if(!$cache_uri){
				return;
			}
			$limit = 3;
			$limit_start = ($pnow - 1) * $limit;
			$pdo = MyPdoIndex::init($config);
			$sql = "select id,title,price,banner from shop_free limit {$limit_start},{$limit}";
			$res = $pdo->dql($sql,array());
			//{id: "3", title: "af210", price: "2.00", banner: "/shop_img/110101/1/2/20190330115644.jpg"}
			$data = array(
				'expire'=>(time() + 10000)*1000,		//过期时间
				'data'=>array()
			);
			if($res){
				foreach($res as $v){
					$tmp_arr = array(
						$v['id'],
						$v['title'],
						$v['price'],
						$v['banner']
					);
					$data['data'][] = $tmp_arr;
				}
			}
			$res2 = json_encode($data);
			echo $res2;
			UpyunAddFile($config,$cache_uri,$res2);
			break;








		//获取商户或商品列表数据
		case 'GetStoreOrGoodsInfoList':
			$goods_type1 = I('goods_type1','post');
			$goods_type2 = I('goods_type2','post');
			$goods_type3 = I('goods_type3','post');
			$city_code = I('city_code','post');
			$gs_type = intval(I('gs_type','post'));	//0：商品，1：商户
			$search = I('search','post');
			$pnow = intval(I('pnow','post'))>0?intval(I('pnow','post')):1;
			$cache_name = I('cache_name','post');

			if(!$goods_type1 || !$goods_type2 || !$goods_type3 || !$city_code || !is_int($gs_type) || !$pnow || !$db_name || !$db_host){
				exit('err1');
			}

			$pdo = MyPdoIndex::init($config);

			$size = 10;
			$limit_start = ($pnow -1) * $size;

			//限制limi起步值过大，导致拖库
			if($limit_start > 3000){
				echo 'err2';exit;
			}

	      	//拼接sql语句
	      	if($gs_type == 1){ 	//获取商户信息列表
	      		$fields = 'id,banner,name,info,utag1,utag3';
	      		if($search){
	      			$sql = "select {$fields} from shop_store where stat =2 and name = ? limit 1000 union select {$fields} from shop_store where stat =2 and name like ? limit 1000 union select {$fields} from shop_store where stat =2 and name like ? and id < 100000 limit {$limit_start},{$size}";
	      			$arr = array($search,"{$search}%","%{$search}%");
	      		}else{
	      			$sql = "select {$fields} from shop_store where stat = 2 order by hit limit {$limit_start},{$size}";
	      			$arr = array();
	      		}
	      	}else{ 				

	      		//获取商品信息列表

	      		//$fields = 'g.id,g.banner,g.title,g.price,g.utag1,g.utag3,s.utag1 as s_utag1';
	      		$fields = 'g.id,g.banner,g.title,g.price,g.utag1,s.utag1 as s_utag1';
	      		if($goods_type3 != 'none'){
	      			$where = ' where g.goods_stat = 2 and g.store_stat = 1 and g.tid3 ='.intval($goods_type3);
	      		}else if($goods_type2 != 'none'){
	      			$where = ' where g.goods_stat = 2 and g.store_stat = 1 and g.tid2 ='.intval($goods_type2);
	      		}else if($goods_type1 != 'none'){
	      			$where = ' where g.goods_stat = 2 and g.store_stat = 1 and g.tid1 ='.intval($goods_type1);
	      		}else{
	      			$where = ' where g.goods_stat = 2 and g.store_stat = 1 ';
	      		}
	      		if($search){
	      			$sql = "select {$fields} from shop_goods g use index(b) left join shop_store s on g.store_id = s.id {$where} and g.title = ? limit 1000 union select {$fields} from shop_goods g use index(b) left join shop_store s on g.store_id = s.id {$where} and g.title like ? limit 1000 union select {$fields} from shop_goods g use index(c) left join shop_store s on g.store_id = s.id {$where} and g.title like ? and g.id < 2000000 limit {$limit_start},{$size}";
	      			$arr = array($search,"{$search}%","%{$search}%");
	      		}else{
		      		$sql = "select {$fields} from shop_goods g left join shop_store s on g.store_id = s.id {$where} order by g.hit limit {$limit_start},{$size}";
		      		$arr = array();
	      		}
	      	}
	      	//检测同SQL语句是否操作太频繁
	      	$tag = md5($sql.implode($arr));
	      	$sql_tag2 = "select time from shop_upyun_utime where tag = ?";
	      	$res_tag2 =$pdo->dql($sql_tag2,array($tag),1);
	      	$expire = 30;
	      	if($res_tag2['time'] + $expire > time()){
	      		exit('err3');	//操作太频繁
	      	}

	      	//查询
	      	$res = $pdo->dql($sql,$arr);
	      	$time = time();
	      	$data['time'] = $time;
	      	$data['data'] = array();

	      	//echo $res2 = json_encode($data);exit;
	      	if($res){
	      		$full_data = array();
	      		if($gs_type == 1){		//商户
   					foreach($res as $v){
		      			$tmp_data = array(
		      				$v['id'],
		      				$v['banner'],
		      				ChangeChar($v['name'],1),
		      				ChangeChar($v['info'],1),
		      				$v['utag1'],
		      				$v['utag3'],
	      				);
	      				$full_data[] = $tmp_data;
		      		}
	      		}else{					//商品
		      		foreach($res as $v){
		      			$tmp_data = array(
		      				$v['id'],
		      				$v['banner'],
		      				ChangeChar($v['title'],1),
		      				ChangeChar($v['price'],1),
		      				$v['utag1'],
		      				$v['s_utag1']
	      				);
	      				$full_data[] = $tmp_data;
		      		}
	      		}
	      		$data['data'] = $full_data;
	      	}
	      	echo $res2 = json_encode($data);

	//exit;
	      	//写入upyun
	      	$path = '/data_cache/'.$cache_name.'.html';
	      	UpyunAddFile($config,$path,$res2);	//缓存数据到 tp-shop-cache

	      	//记录同sql语句对upyun的操作时间
	      	$sql_tag = "replace into shop_upyun_utime values(?,?)";
	      	$res_tag = $pdo->dml($sql_tag,array($tag,$time));
			break;











		//获取商户详情
		case 'GetStoreDetail':
			$store_id = intval(I('store_id','post'));
			$cache_uri = $_POST['cache_name'];
			if(!$store_id || !$cache_uri){
				exit('err');
			}

			$pdo = MyPdoIndex::init($config);
			$fields = 'id,name,addr,info,phone,wx,qq,banner,utag1,utag2,utag3,stat';
			$sql = "select {$fields} from shop_store where id = ?";
			$res = $pdo->dql($sql,array($store_id),1);
			if($res){
				$tmp_arr = array(
					$res['id'],
					ChangeChar($res['name'],1),
					ChangeChar($res['addr'],1),
					ChangeChar($res['info'],1),
					$res['phone'],
					$res['wx'],
					$res['qq'],
					$res['banner'],
					$res['utag1'],
					$res['utag3']
				);
				$res2 = json_encode($tmp_arr);
				$utag1 = $res['utag1'];

				if($res['stat'] != 2){	//商户非正常状态
					$res2 = '[]';
					$utag1= 'none';
				}


				//判断并更新upyun操作时间
				if(intval($res['utag2']) + 6 > time()){	
					echo $res2;
					exit;	//操作太频繁
				}else{
					//更新upyun操作时间标记
					$sql3 = "update shop_store set utag2 = ? where id = ?";
					$res3 = $pdo->dml($sql3,array(time(),$store_id));
				}

			}else{
				$res2 = '[]';
				$utag1= 'none';
			}
			
			echo $res2;
      		$upyun_path_update = $cache_uri.'.html';
      		$upyun_path_update_utag1 = $cache_uri.'_utag1.html';
			UpyunAddFile($config,$upyun_path_update,$res2);
			UpyunAddFile($config,$upyun_path_update_utag1,$utag1);





			exit;
			$store_id = intval(I('store_id','post'));
			$cache_name = $_POST['cache_name'];
			if(!$store_id || !$cache_name){
				exit('err');
			}

			$pdo = MyPdoIndex::init($config);
			$fields = 'id,name,addr,info,phone,wx,qq,banner,utag1,utag2,utag3';
			$sql = "select {$fields} from shop_store where stat=2 and id = ?";
			$res = $pdo->dql($sql,array($store_id),1);
			if($res){
				$tmp_arr = array(
					$res['id'],
					ChangeChar($res['name'],1),
					ChangeChar($res['addr'],1),
					ChangeChar($res['info'],1),
					$res['phone'],
					$res['wx'],
					$res['qq'],
					$res['banner'],
					$res['utag1'],
					$res['utag3']
				);
				$res2 = json_encode($tmp_arr);

				echo $res2;

				//判断并更新upyun操作时间
				if(intval($res['utag2']) + 10 > time()){
					exit;	//操作太频繁
				}else{
					$sql3 = "update shop_store set utag2 = ? where id = ?";
					$res3 = $pdo->dml($sql3,array(time(),$store_id));
					if($res3){
			      		$upyun_path_update = $cache_name.'.html';
						$res4 = UpyunAddFile($config,$upyun_path_update,$res2);
						//$upyun_path_update_time = '/detail_store/'.$cache_name.'_expire.html';
						//UpyunAddFile($config,$upyun_path_update_time,$res['utime']);
					}else{
						exit;	//更新操作时间失败
					}
				}
			}

			break;





		//获取商户下的商品列表
		case 'GetGoodsListForStore':
			$store_id = intval($_POST['store_id']);
			$cahce_url = $_POST['cache_url'];
			if(!$store_id || !$cahce_url){
				exit;
			}
			$pdo = MyPdoIndex::init($config);
			$sql = 'select utag3 from shop_store where id = ?';
			$res = $pdo->dql($sql,array($store_id),1);

			$data['utag3'] = 0;
			$data['data'] = array();
			if($res && $res['utag3']){
				$data['utag3'] = $res['utag3'];
				$sql2 = 'select id,banner,title,price,utag1,utag3 from shop_goods where store_id = ? and goods_stat = 2 and store_stat = 1 order by id desc';
				$res2 = $pdo->dql($sql2,array($store_id));
				if($res2){
					$tmp = array();
					foreach($res2 as $v){
						$tmp[] = array(
							$v['id'],
							$v['banner'],
							ChangeChar($v['title'],1),
							$v['price'],
							$v['utag1'],
							$v['utag3']
						);
					}
					$data['data'] = $tmp;
				}
			}
			$res2 = json_encode($data);
			echo $res2;
			$upyun_path_update = $cahce_url.'.html';
			UpyunAddFile($config,$upyun_path_update,$res2);
			break;






		//获取指定商品详情
		case 'GetGoodsDetail':
			$goods_id = intval(I('goods_id','post'));
			$cache_name = $_POST['cache_name'];
			$upyun_path_update = $cache_name.'.html';
			$upyun_path_update_utag1 = $cache_name.'_utag1.html';
			if(!$goods_id || !$cache_name){
				exit('err');
			}

			$pdo = MyPdoIndex::init($config);
			//$fields = 'id,store_id,title,price,info,number,banner,utag1,utag2';
			//$sql = "select {$fields} from shop_goods where goods_stat = 2 and id = ?";
			$fields = 'g.id,g.store_id,g.title,g.price,g.info,g.number,g.banner,g.utag1,g.utag2,g.utag3,s.utag1 as s_utag1';
			$sql = "select {$fields} from shop_goods as g join shop_store as s on g.store_id = s.id where g.goods_stat = 2 and g.id = ?";
			$res = $pdo->dql($sql,array($goods_id),1);
			if($res){
				//echo $res2 = json_encode($res);
				$res_tmp = array(
					$res['id'],
					$res['store_id'],
					$res['banner'],
					ChangeChar($res['title'],1),
					$res['price'],
					ChangeChar($res['info'],1),
					$res['number'],
					$res['utag1'],
					$res['utag3'],
					$res['s_utag1']
				);
				$res2 = json_encode($res_tmp);

				echo $res2;

				//判断并更新upyun操作时间
				if(intval($res['utag2']) + 10 > time()){
					exit;
				}else{
					$sql3 = "update shop_goods set utag2 = ? where id = ?";
					$res3 = $pdo->dml($sql3,array(time(),$goods_id));
					if($res3){
						UpyunAddFile($config,$upyun_path_update,$res2);
						UpyunAddFile($config,$upyun_path_update_utag1,$res['utag1']);
					}else{
						exit;	//更新操作时间失败
					}
				}
			}
			break;






	
		//获取指定商品的图片列表
		case 'GetGoodsImgList':
			$goods_id = intval(I('goods_id','post'));
			$cache_name = $_POST['cache_name'];
			$upyun_path_update = $cache_name.'.html';
			//echo $upyun_path_update;exit;
			if(!$goods_id || !$cache_name){
				exit('err');
			}
			$pdo = MyPdoIndex::init($config);
			
			$sql = 'select utag3 from shop_goods where id = ?';
			$res = $pdo->dql($sql,array($goods_id),1);
			$data['utag3'] = 0;
			$data['imgs'] = array();
			if($res){
				$data['utag3'] = $res['utag3'];	
				$sql2 = "select addr from shop_img where gid = ?";
				$res2 = $pdo->dql($sql2,array($goods_id));
				if($res2){
					foreach($res2 as $v){
						$imgs[] = $v['addr'];
					}
					$data['imgs'] = $imgs;
				}
			}
			echo $res2 = json_encode($data);
			UpyunAddFile($config,$upyun_path_update,$res2);
			break;
	}

   












	/*
		### 记录朋友帮砍的价格
		$order_id     砍价订单的id  (非订单号)
		$price_free   帮砍的价格
		return        记录成功返回true,失败返回false
	*/
	function RecordFreeUser($pdo,$order_numb,$openid,$nickName,$headerImg,$price_free){
		$sql5 = "select id from shop_free_order_user where order_numb=? and openid = ?";
		$arr5 = array($order_numb,$openid);
		$res5 = $pdo->dql($sql5,$arr5,1);
		if($res5){
			return false;	//该用户已经帮砍过价了
		}
		//记录参与砍价的用户
		$sql4 = "insert into shop_free_order_user values(null,?,?,?,?,?,?)";
		$arr4 = array(
			$order_numb,
			$openid,
			$nickName,
			$headerImg,
			$price_free,
			time()
		);
		$res4 = $pdo->dml($sql4,$arr4);
		if($res4){
			return true;
		}else{
			return false;
		}
	}